package org.opencare.plugins.listener;

import java.util.List;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opencare.plugins.model.MessageBuilder;
import org.opencare.plugins.model.MessageDao;
import org.opencare.plugins.model.MessageObject;
//import org.opencare.plugins.model.TwitterClient;
import org.opencare.plugins.model.TwitterClient;

public class PluginListener implements javax.jms.MessageListener {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	private Connection jmsConn;
	private Session session;
	private Topic topic;
	private MessageBuilder builder;
	private MessageDao messageDao;
	private TwitterClient twitterClient;

	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public void setTwitterClient(TwitterClient twitterClient) {
		this.twitterClient = twitterClient;
	}

	public PluginListener(String jmsUrl, String topicName, String clientId,
			MessageBuilder builder) {

		this.builder = builder;

		logger.debug("jmsUrl:" + jmsUrl);
		logger.debug("topicName:" + topicName);
		logger.debug("clientId:" + clientId);

		try {

			ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
					jmsUrl);

			jmsConn = factory.createConnection();
			jmsConn.setClientID(clientId);
			session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			topic = session.createTopic(topicName);
			MessageConsumer consumer = session.createDurableSubscriber(topic,
					topic.getTopicName());
			consumer.setMessageListener(this);
			jmsConn.start();

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated constructor stub
	}

	public void onMessage(Message message) {
		// TODO Auto-generated method stub
		String rssText = null;

		try {
			logger.debug("Receive message:" + message.getJMSMessageID());
			String msgText;

			if (message instanceof TextMessage) {
				msgText = ((TextMessage) message).getText();
			} else { // If it is not a TextMessage...
				msgText = message.toString();
			}

			logger.debug("Content: " + msgText);
			
			List<MessageObject> msgList = builder.build(msgText);

			// Store
			for (MessageObject msg : msgList) { 
				messageDao.store(msg);
				String status = twitterClient.tweet(msg);
				logger.debug("Tweet: " + status);
			}

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
